/*页面展示通用js，主要用于页面初始化配置 */
var pageUpper = {
	items : null,
	contactStr:'lsS'
};

/**
 * 所有tab页面初始化查询区下拉框总方法
 * 
 * @param paraMap
 * @param paraNameMap
 * @param callBack
 */
function initSel(initsels, paraMap, paraNameMap, itemConfig, callBack) {

	itemConfig = itemConfig || {};
	itemConfig.postData = paraMap;
	pageUpper.items = new Item(itemConfig);
	pageUpper.items.create();
	
	initPageSel(initsels);
	//给所有的下拉框选项默认选中
	for(var i in initsels){
		var sel=initsels[i].element;
		var selId=sel.substring(1);
		
		var defLable={};
		defLable.code=paraMap[selId];
		initsels[i].defLabel=defLable;
	}
	$.select.initSels(initsels , paraMap, paraNameMap, function() {
		
		refreshTxtReport();
		
		if ($.isFunction(callBack)) {
			callBack();
		}

		for(var i in initsels){
			$(initsels[i].element).combobox('setOption', {
				value : paraMap[initsels[i].element.substring(1)]
			});
		}
		bindDiffChange(pageUpper.items);
		
		/*var diffChanges=$('select[diffChange="true"]');
		if(diffChanges.length>0){
			refreshDiySel();
		}*/
			
	});

}


/**
 * 所有明细页面初始化查询区下拉框总方法
 * 
 * @param paraMap
 * @param paraNameMap
 * @param callBack
 */
function initDelSels(initsels,params, paraNameMap, itemConfig, callBack) {

	initSel(initsels,params, null, itemConfig, function(){
		
		//给所有的下拉框选项默认选中
		/*for(var i in initsels){
			
			var sel=initsels[i];
			var element=sel.element;
			
			var selId=element.substring(1);
			
			if (paraMap[selId]) {
				$(element+" option").eq(0).before('<option value="">所有</option>');
			}
			
			$(element).combobox('setOption', {
				value : params[selId]
			});
		}*/
		
		if ($.isFunction(callBack)) {
			callBack();
		}
		
	});
}

/**
 * 所有页面查询方法
 * 
 * @param btnId
 * @param doClick
 */
function queryClick(btnId, doClick, callBack) {

	btnId = btnId || 'query_btn';

	// 查询按钮绑定click事件
	$('#' + btnId).click(function() {

		/*$('.page-content form').each(function() {
			$(this).get(0).reset();
		});
		$('.page-content select').each(function() {
			$(this).empty();
		});*/
		
		// 刷新选中自定义下拉框（如：纬度）
		$(".js-reset-select").each(function(){
	        var selectedOpt = $(this).find("option[selected=selected]"),
	            firstOpt = $(this).find("option:eq(0)"),
	            value = selectedOpt.attr("value") ? selectedOpt.attr("value") : firstOpt.attr("value");
	        $(this).combobox("setOption",{value: value});
	    });
	    
		if (doClick) {
			doClick();
		}
		
		refreshTxtReport();
		pageUpper.items.refresh();
		
		if ($.isFunction(callBack)) {
			callBack();
		}

	});
}

/**
 * 明细页面查询方法
 * @param btnId
 * @param doClick
 */
function delQueryClick(btnId, doClick, callBack) {

	btnId = btnId || 'query_btn';

	// 查询按钮绑定click事件
	$('#' + btnId).click(function() {
		//查询前将值赋值给隐藏域
		setHideParams($.utils.getFormData());
		
		if (doClick) {
			doClick();
		}
		
		pageUpper.items.refresh();
		if ($.isFunction(callBack)) {
			callBack();
		}
	});
}

function parseParam(param,separator){
	 separator=separator||'/';
	 var defParam={ name:'', value:'' };
	 $.extend(defParam,param);
	 var names=defParam.name.split(separator),
	 values=defParam.value.split(separator);
	 var paraMap={};
	 for(var i in names){
		 var item=names[i];
		 paraMap[item]=values[i];
	 }
	 return paraMap;
};

function searchParam(formId){
	formId=formId||'queryForm';
	var params=$('#' + formId).find('*[allowserialize!="no"]').serializeArray();
	return params;
}

//刷新java表单类报表
function refreshTxtReport(params){
	var divArray = $.find(".page-content div[dynDiv=true]"); //获得所有需要动态加载的DIV
	for(var i=0; i<divArray.length; i++){
		var moduleCode = $(divArray[i]).attr("moduleCode");
		if(!params){
			params=getAllParams("queryForm_"+moduleCode);
		}
		
		var reqUrl = $(divArray[i]).attr("reqUrl");

		$("#div_"+moduleCode).showLoading({ "parent":"#div_"+moduleCode}).load(jsContextPath+reqUrl, params, function(){
			$(this).hideLoading();
			if($(".programTree").length>0){
				$(".programTree").flowProgress();
			}
	   });
		
	}
};

//获取url的参数，并转成map
function getParamsMap() {
	var search = window.location.search;
	search = search.replace('?', '');
	var arr = search.split('&');
	var map = {};
	var reg = new RegExp('^' + pageUpper.contactStr);

	for ( var i in arr) {
		var o = arr[i];
		var param = o.split('=');
		var name = param[0];
		name = name.replace(reg, '');
		var value = param.length > 1 ? param[1] : '';
		map[name] = decodeURI(decodeURI(value));
	}
	return map;
};

// 设置hidden参数到form元素里
function setHideParams(paraMap, el) {

	$el = $(el || '#queryForm');

	for ( var key in paraMap) {
		var obj = $el.find('*[name="' + key + '"]');
		if (0 === obj.length) {
			var paraValue = paraMap[key];
			var hidden = $('<input type="hidden"/>');
			hidden.attr( {
				'id' : key,
				'name' : key,
				'value' : paraValue
			});
			$el.append(hidden);
		}/*else{
			obj.val(paraMap[key]);
		}*/
	}
};


//绑定不同维度报表刷新
function bindDiffChange(ptreeItem){
	var select = $.find('select[diffChange="true"]');
	$(select).each(function() {
		
		var options=$(this).find('option');
		for(var i =0 ;i<options.length;i++){
			var option=options[i];
			option=option.value;
			
			var selValue=optionToArray(option);
			if(i!=0){
				for(var k in selValue){
					$('#'+selValue[k]).hide();
				}
			}
			
		}
		
		$(this).combobox({
			select: function( event,ui ){
				var selValue=ui.item.value;
				
				refreshOrInitChart(selValue,ptreeItem.option.items);
				
			}
		});
			
	});
	
}

//获取各种参数值（树上的值,本身报表上方的表单+页面主表单）
function getAllParams(curtFormId,otherParams){
	var params={};
	
	params=$.extend(true, params, paraMap);
	
	var mainForm=$.utils.getFormData('queryForm');
	params=$.extend(true, params, mainForm);
	
	if(curtFormId){
		var curtForm=$.utils.getFormData(curtFormId);
		
		params=$.extend(true, params, curtForm);
		
		var monthsDates=$('#'+curtFormId +' .js-kit-icon-datebox');
		if(monthsDates.length>0){
			for(var i =0 ;i < monthsDates.length; i++){
				var dateMonth=$(monthsDates[i]).attr('id');
				if(dateMonth){
					dateMonth=$('#'+dateMonth+'_vel');
					var dateName=$(dateMonth).attr('name');
					var dateId=$(dateMonth).attr('id');
					
					if(dateId.indexOf('_START')>-1||dateId.indexOf('_END')>-1){
						params[dateName]=substrMonth($('#'+dateId).val());
					}
				}
				
			}
		}
		
	}
	if(otherParams){
		params=$.extend(true, params, otherParams);
	}
	
	return params;
}

//多维度下拉框刷新事件
function refreshDiySel(){
	
	$('select[diffChange="true"]').each( function(){
		
		var form = $(this).parents('form');
		
		form.find('select[diffChange!="true"]').each( function(){
			bindDiySel([ {name:$(this).attr('id')} ]) ;
		}); 
		
	});
	
}
//绑定自定义下拉框刷新事件
function bindDiySel(selIds){
	
	if(selIds&&selIds.length>0){
		for(var i in selIds){
			var selId=selIds[i].name;
			
			$('#'+selId).combobox({
				select: function( event,ui ){
					var item = ui.item;
					var select = $(item).parent();
					
					var sId = $(select).attr("id");
					
					refreshVisibleChart(sId);
				}
			});
		}
	}
	
}

//刷新当前报表
function refreshVisibleChart(selId){
	var chart=$('#'+selId).parents('.kit-col');
	var chartForm=$(chart).find('form');
	var crtSel=$(chartForm).find('select[diffChange="true"]');
	selValue=$(crtSel).val();
	refreshChart(selValue,chartForm);
}

function refreshChart(selValue,form){
	if(selValue){
		
		selValue=optionToArray(selValue);
		
		for(var i in selValue){
			$('#'+selValue[i]).updateChart({
				  params:getAllParams($(form).attr('id'))
			});
		}
	}
}

//刷新或创建报表
function refreshOrInitChart(selValue,itemConfig,updateFun,configObj){

	var sel;
	
	selValue=optionToArray(selValue);
	
	for(var k in selValue){
		
		var selId=selValue[k];
		var isInit=$('#'+selId).attr('isinit');
		
		sel=$('#'+selId);
		
		var opt={};
		
		var ptreeIt=itemConfig;
		
		for(var it in ptreeIt){
        	if(it==selId){
        		opt=ptreeIt[it];
        		break;
        	}
        }
        
		if (!isInit) {
			$('#'+selId).attr('isinit','1');
			if(opt.init){
				opt.init();
			}
		}else{
			var chart=$('#'+selValue[0]).parents('.kit-col');
			var chartForm=$(chart).find('form');
			if ($.isFunction(updateFun)) {
				updateFun();
			}else{
				
				var config={params:getAllParams($(chartForm).attr('id'))};
				if(configObj && configObj.length > 0 ){
					config.reportType=configObj[k];
				}
				$('#'+selId).updateChart(config);
			}
			
		}
		
		
	}
	
	var code=$(sel).parents('.kit-col').attr('id');
	
	$('#'+code+' .chart').each( function(){
		
		if( $.inArray( $(this).attr('id') , selValue) == -1){
			$(this).hide();
			
		}else{
			$(this).show();
		}
	});
	
}

//将option的值分割转换数组
function optionToArray(selValue){
	if(selValue.indexOf(';')>-1){
		selValue=selValue.split(';');
	}else{
		selValue=[selValue];
	}
	return selValue;
}

/**
 * //打开下钻窗口
 * @param url
 * @param otherParams  传需要处理的特殊参数
 */

function openDel(url,curtFormId,otherParams) {
	var urlStr = jsContextPath + url;
	
	var data = getAllParams(curtFormId,otherParams);
	
	for(var i in data){
		data[i]=decodeURI(encodeURI(data[i]));
	}
	
	var params=$.param(data);

	urlStr += "?" + params;
	
	$.utils.openFullWin(urlStr);
}


/**
 * format%
 */
function formatPercent(x){
	if(x==""||x=='null'||x==undefined){
		return "0.00%";
	}
	var f_x = parseFloat(x);
	if (isNaN(f_x))
	{
	return false;
	}
	var f_x = Math.round(x*100)/100;
	var s_x = f_x.toString();
	var pos_decimal = s_x.indexOf('.');
	if (pos_decimal < 0)
	{
	pos_decimal = s_x.length;
	s_x += '.';
	}
	while (s_x.length <= pos_decimal + 2)
	{
	s_x += '0';
	}
	return s_x+"%";
}


//初始化页面隐藏相应下拉框
function initPageSel(initSels){
	//var sun = initSels.length;//记录查询条件的个数
	var v = 0;//记录隐藏查询条件的个数.. 如果 sun = v 则隐藏按扭
	for (var i in paraMap){
		for(var j in initSels){
			var sel=initSels[j].element;
			var selId=sel.substring(1);
			if(i==selId){
				v ++;
				$("#div_"+selId).hide();
			}
		}
	}
	/*if(sun==v){// 如果 sun = v 则隐藏按扭
		$("#head-search").hide();
		$(".page-content").css('top','0px'); 
	}*/
}

//普通URL转换成MAP
function getNormalUrlMap(){
	pageUpper.contactStr='';
	return getParamsMap();
}

//对于单项工程，对URL参数转为MAP
function getSingleItems(){
	var sin = getParamsMap();
	var name = sin.paramsFullPath == null || sin.paramsFullPath == undefined ? '' : sin.paramsFullPath.split('%2F');
	var value = sin.valuesFullPath == null || sin.valuesFullPath == undefined ? '' : sin.valuesFullPath.split('%2F');
	for ( var i = 0; i < name.length; i++) {
		sin[name[i]]=value[i];
	}
	return sin;
}

function substrMonth(month){
	return month.length>2?month.substring(4,6):month;
}

function monthSelect(){
	var form=$(this).parents('form');
	var monthDates=$(form).find('.js-kit-icon-datebox');
	
	if(monthDates.length>1){
		var start=$('#'+$(monthDates[0]).attr('id')+'_vel').val();
		start=substrMonth(start);
		start=parseInt(start);
		var end=$('#'+$(monthDates[1]).attr('id')+'_vel').val();
		end=substrMonth(end);
		end=parseInt(end);
		
		if(start>end){
			alert('开始月份不能大于结束月份！');
			return;
		}else if(end<start){
			alert('结束月份不能小于开始月份！');
			return;
		}
	}
	
	
	var refreshType=$(monthDates[0]).attr('refreshType');
	var moduleCode=$(monthDates[0]).attr('moduleCode');
	
	var formId="queryForm_"+moduleCode;
	var params=getAllParams(formId);
	
	
	switch(refreshType){
	   case 'chart':
		   var crtChart=$('#'+moduleCode+' .chart');
		   var diffSel=$('#'+moduleCode).find('select[diffChange="true"]');
		   if(diffSel.length>0){
			   refreshChart($(diffSel).val(),'#'+formId);
		   }else{
			   $.each(crtChart,function(){
				   $(this).updateChart({
						  params:params
					});
			   });
		   }
		   break; 
	   case 'grid':
		   $('#'+moduleCode).jqGrid('setGridConfig', {
				paramObj : params
			});
			$('#'+moduleCode).doFind();
		   break;
	   case 'div':
		   refreshTxtReport(params);
		   break;
	}
}

function initInputs(paraMap) {
	for(var i in paraMap){
		if($('#'+i).is('input')) {
			$('#'+i).val(paraMap[i]);
			$('#'+i+'_NAME').val(paraNameMap[i]);
		}
	}
}